package cn.com.bsoft.mobile.service

import cn.com.bsoft.mobile.dao.FeedbackDao
import cn.com.bsoft.mobile.dao.MobileArchiveDao
import cn.com.bsoft.mobile.dao.MobileUserDao
import cn.com.bsoft.mobile.entity.Feedback
import cn.com.bsoft.mobile.entity.MobileUser
import cn.com.bsoft.mobile.model.FeedbackReq
import cn.com.bsoft.mobile.model.FeedbackRsp
import cn.com.bsoft.mobile.model.QueryFeedbackReq
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.jpa.domain.Specifications
import java.util.*
import javax.persistence.criteria.Join

interface FeedbackService{
    fun create(req: FeedbackReq):Feedback
    fun query(req:QueryFeedbackReq):List<Feedback>
}

fun Feedback.toRsp():FeedbackRsp{
    var rsp = FeedbackRsp()
    rsp.username = user?.loginName
    rsp.id = uuid
    rsp.body = body
    rsp.createDate = createDate
    archives?.forEach {
        rsp?.archives?.add(it.uuid!!)
    }

    return rsp
}

class DefaultFeedbackServiceImpl:FeedbackService{


    @Autowired
    lateinit var userDao:MobileUserDao

    @Autowired
    lateinit var feedbackDao:FeedbackDao

    @Autowired
    lateinit var archiveDao:MobileArchiveDao

    override fun create(req: FeedbackReq): Feedback {
        val user = userDao.findOne(req.username)

        var feedback = Feedback()

        feedback.user = user
        feedback.body = req.body

        req.archives.forEach {
            val archive = archiveDao.findOne(it)

            feedback.archives.add(archive)
        }

        return feedbackDao.saveAndFlush(feedback)
    }

    override fun query(req: QueryFeedbackReq): List<Feedback> {
        var w: Specifications<Feedback> = Specifications.where({
            _,_,cb ->
            cb.equal(cb.literal(1),1)
        })

        w = w.and({
            root, query, cb ->
            val join: Join<*, *> = root.join<MobileUser,Feedback>(Feedback::user.name)
            cb.equal(join.get<String>(MobileUser::loginName.name),req.username )
        })

        if (req.begin != null && req.end != null){
            w = w.and({
                root, query, cb ->

                cb.between(root.get<Date>(Feedback::createDate.name),req.begin,req.end )
            })
        }

        return feedbackDao.findAll(w)
    }

}